const sha1 = require("sha1")

const config = require("../config")
const { getUserDataAsync, parseXmlData, formatMsg } = require("../libs/utils")
const reply = require("./reply")

module.exports = () => {
    return async (req, res, next) => {
        const { signature, echostr, timestamp, nonce } = req.query
        const { token } = config
        const str = [token, timestamp, nonce].sort().join("")
        const sha1str = sha1(str)
        if (req.method === "GET") {
            // GET请求用于验证服务器的有效性
            if (sha1str == signature) {
                res.set("Content-Type", "text/plain");
                res.send(echostr);
            } else {
                res.send(false)
            }
        } else if (req.method === "POST") {
            // POST用于接收用户发送的消息
            if (sha1str != signature) {
                // post请求不是来源于微信
                res.send("error")
                return
            }
            // 获取微信发送的消息
            const xml_data = await getUserDataAsync(req)
            let user_data = await parseXmlData(xml_data)
            user_data = formatMsg(user_data)
            // 使用reply.js
            const replyMessage = await reply(user_data)
            console.log(replyMessage)
            // 将消息结构发送到微信服务器
            res.send(replyMessage)
        }
    }
}